package com.whfc.common.third.mas.impl;

import com.alibaba.fastjson.JSONObject;
import com.whfc.common.exception.BizException;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.third.mas.entity.LoginResponseDTO;
import com.whfc.common.third.mas.MasLoginApi;
import com.whfc.common.third.mas.MasProperties;
import com.whfc.common.util.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;

/**
 * MAS登录API实现类
 */
@Component
public class MasLoginApiImpl implements MasLoginApi {

    private static final Logger logger = LoggerFactory.getLogger(MasLoginApiImpl.class);

    private final MasProperties masProperties;

    public MasLoginApiImpl(MasProperties masProperties) {
        this.masProperties = masProperties;
    }

    @Override
    public LoginResponseDTO login(String username, String password, String deviceType, String urlSuffix)
            throws BizException {
        logger.info("MAS系统用户登录，username:{}", username);

        // 构建完整的登录URL
        String baseUrl = masProperties.getApiUrl();
        if (urlSuffix != null && !urlSuffix.isEmpty()) {
            baseUrl = baseUrl.endsWith("/") ? baseUrl + urlSuffix : baseUrl + "/" + urlSuffix;
        } else {
            baseUrl += "/login";
        }

        // 构建请求参数
        Map<String, String> params = new HashMap<>();
        params.put("username", username);
        params.put("password", password);
        if (deviceType != null) {
            params.put("deviceType", deviceType);
        }

        try {
            // 发送POST请求，使用配置的超时时间
            String response = HttpUtil.doPost(baseUrl, params, null, masProperties.getConnectTimeout(),
                    masProperties.getReadTimeout());
            logger.info("MAS系统登录响应: {}", response);

            // 解析响应结果
            LoginResponseDTO loginResponse = JSONObject.parseObject(response, LoginResponseDTO.class);

            // 检查响应是否成功
            if (loginResponse == null) {
                throw new BizException(ResultEnum.NETWORK_ERROR.getCode(), "MAS系统登录失败，响应数据为空");
            }

            if (loginResponse.getCode() == null || loginResponse.getCode() != 200) {
                throw new BizException(ResultEnum.FAILURE.getCode(),
                        loginResponse.getMsg() != null ? loginResponse.getMsg() : "MAS系统登录失败");
            }

            return loginResponse;
        } catch (BizException e) {
            logger.error("MAS系统登录业务异常: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            logger.error("MAS系统登录异常: {}", e.getMessage(), e);
            // 根据异常类型判断是否为超时错误
            String errorMessage = "MAS系统登录失败，请稍后重试";
            String errorCode = ResultEnum.NETWORK_ERROR.getCode();

            // 检查异常消息中是否包含超时相关关键词
            if (e.getMessage() != null && (e.getMessage().contains("timeout") || e.getMessage().contains("超时"))) {
                errorCode = ResultEnum.NETWORK_TIMEOUT.getCode();
                errorMessage = "MAS系统登录超时，请稍后重试";
            }

            throw new BizException(errorCode, errorMessage);
        }
    }
}